import { Button, message } from "antd";
import { ChangeEvent, ChangeEventHandler, useEffect, useState } from "react";
import { getStorageManager } from '@/storage'
import { sanitizeFileName } from '@/storage/utils';
import { parseFromCSV, stringifyToCSV } from '@/storage/csv'

export default function CSVList() {

    const [list, setList] = useState<any[]>([])

    // 保存数组数据到csv
    const saveArray = () => {
        const csvStorage = getStorageManager().getCSVStorage()


        // 将json转化为csV数据
        stringifyToCSV([
            [
                "1",
                "2",
                "3"
            ],
            [
                "a",
                "b",
                "c"
            ],
            [
                "a1",
                "a2",
                "a3"
            ]
        ]).then((stringData: any) => {
            // console.log(stringData, 'stringData')
            csvStorage.write('a.csv', new Blob([stringData]));
        })
    }

    // 读取csv数据到array
    const getArrayData = (fullPath: string) => {
        getStorageManager().getCSVStorage().read(fullPath, 'Text').then((res: any) => {
            // 将csv转化为json
            parseFromCSV(res).then(jsonData => {
                console.log(jsonData, 'jsonData')
            })
        })
    }

    // 获取列表
    const getList = () => {
        const csvStorage = getStorageManager().getCSVStorage();
        csvStorage.list().then(list => {
            setList(list)
        })
    }

    // 上传CSV
    const onFileChange: ChangeEventHandler<HTMLInputElement> = (e: ChangeEvent<HTMLInputElement>) => {
        const csvStorage = getStorageManager().getCSVStorage()
        const files = [].slice.call(e.target.files)
        if (!files || !files.length) return

        const read = (file: File) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader()
                reader.onload = (readerEvent) => {
                    const text = readerEvent.target!.result
                    resolve({
                        text,
                        fileName: file.name
                    })
                }
                reader.readAsText(file)
            })
        }

        Promise.all(files.map(read))
            .then((list: any[]) => {
                const ps = list.map(fileItem => csvStorage.write(sanitizeFileName(fileItem.fileName), new Blob([fileItem.text])))
                return Promise.all(ps).then(() => getList())
                    .then(() => {
                        message.info(`${list.length} csv files imported`)
                    })
            })
            .catch(e => {

            })
    }

    // 请求数据
    useEffect(() => {
        getList()
    }, [])

    return <div>
        <span className="load-image-button ant-btn ant-btn-primary">
            <label htmlFor="select_CSV_files">上传CSV文件</label>
            <input
                multiple
                type="file"
                accept=".csv"
                id="select_CSV_files"
                onChange={onFileChange}
                style={{ display: 'none' }}
            />
        </span>
        <Button onClick={saveArray} >保存array</Button>
        <ul>
            {
                list.map(item => {
                    return <li>
                        {item.name}
                        <Button
                            onClick={() => {
                                getArrayData(item.fullPath)
                            }}
                        >查看JSON数据</Button>

                        <Button
                            onClick={() => {
                                getStorageManager().getCSVStorage().read(item.fullPath, 'Text').then((text:any) => {
                                    const blob = new Blob([text])
                                    // 3. 创建下载链接并触发下载
                                    const url = URL.createObjectURL(blob);
                                    const link = document.createElement('a');
                                    link.href = url;
                                    link.download = item.name; // 下载文件名
                                    document.body.appendChild(link);
                                    link.click();

                                    // 4. 清理临时URL
                                    setTimeout(() => {
                                        URL.revokeObjectURL(url);
                                        document.body.removeChild(link);
                                    }, 0);
                                })
                            }}
                        >
                            导出
                        </Button>

                    </li>
                })
            }
        </ul>
    </div>
}